import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Button,
  Input,
  Table,
  Form,
  Modal,
  Divider,
  Select,
  Row,
  Col,
  Alert,
  Popconfirm,
  Pagination,
} from 'antd';
import styles from './style.less';

const FormItem = Form.Item;
const { Option } = Select;
const { Search } = Input;

const ChildDeviceForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleModalVisible,
    handleAdd,
    clearSelect,
    products,
    deviceList,
    dispatch,
    params,
  } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      clearSelect();
      handleAdd(fieldsValue, form);
    });
  };

  const renderOption = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));

  const renderDeviceOption = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.label}
      </Option>
    ));

  const onChange = value => {
    dispatch({
      type: 'devices/fetchDevices',
      payload: { productId: value, notContainId: params.id },
    });
  };

  return (
    <Modal
      title={formatMessage({ id: 'app.dm.devices.child.add' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onCancel={() => handleModalVisible()}
      onOk={okHandle}
    >
      <Form>
        <FormItem style={{ marginTop: 0, marginBottom: 0 }}>
          {form.getFieldDecorator('pid', { initialValue: params.id })(<Input type="hidden" />)}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.devices.child.product' })}
          colon={false}
          style={{ width: 570 }}
        >
          <Select
            allowClear
            style={{ width: '100%' }}
            placeholder={formatMessage({
              id: 'app.dm.devices.child.product.place',
            })}
            onChange={onChange}
          >
            {renderOption(products)}
          </Select>
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.devices.child.label' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('id', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.devices.child.label.place' }),
              },
            ],
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({
                id: 'app.dm.devices.child.label.place',
              })}
            >
              {renderDeviceOption(deviceList)}
            </Select>,
          )}
        </FormItem>
      </Form>
    </Modal>
  );
});

@connect(({ devices, loading }) => ({
  devices,
  loading: loading.models.devices,
}))
@Form.create()
class ChildDeviceManage extends PureComponent {
  state = {
    modalVisible: false,
    selectedRowKeys: [],
  };

  componentDidMount() {
    const { dispatch, params, protocolType } = this.props;
    dispatch({
      type: 'devices/fetch',
      payload: { pid: params.id },
    });
    dispatch({
      type: 'devices/fetchProduct',
      payload: { protocol: protocolType },
    });
  }

  columns = [
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.devices.name' }),
      dataIndex: 'name',
    },
    {
      key: 'productName',
      title: formatMessage({ id: 'app.dm.devices.product' }),
      dataIndex: 'productName',
    },
    {
      key: 'label',
      title: formatMessage({ id: 'app.dm.devices.label' }),
      dataIndex: 'label',
    },
    {
      key: 'type',
      title: formatMessage({ id: 'app.dm.devices.nodeType' }),
      render: (text, record) => {
        if (record.type === 1) {
          return <FormattedMessage id="app.dm.devices.info.type.device" />;
        }
        if (record.type === 2) {
          return <FormattedMessage id="app.dm.devices.info.type.gateway" />;
        }
        return null;
      },
    },
    {
      key: 'state',
      title: formatMessage({ id: 'app.dm.devices.state' }),
      render: (text, record) => {
        if (record.state === 1) {
          return <FormattedMessage id="app.dm.devices.info.notactive" />;
        }
        if (record.state === 2) {
          return <FormattedMessage id="app.dm.devices.info.enable" />;
        }
        if (record.state === 3) {
          return <FormattedMessage id="app.dm.devices.info.disabled" />;
        }
        if (record.state === 4) {
          return <FormattedMessage id="app.dm.devices.info.online" />;
        }
        if (record.state === 5) {
          return <FormattedMessage id="app.dm.devices.info.offline" />;
        }
        return null;
      },
    },
    {
      key: 'lastUpTime',
      title: formatMessage({ id: 'app.dm.devices.lastTime' }),
      dataIndex: 'lastUpTime',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.devices.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleView(record)}>
            <FormattedMessage id="app.dm.devices.table.action.view" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280, fontWeight: 'bold', color: '000' }}>
                <span>
                  {formatMessage({ id: 'app.dm.devices.del.confirm' }, { name: record.name })}
                </span>
              </div>
            }
            onConfirm={() => this.handleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.dm.devices.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleDelete = id => {
    const { dispatch, params } = this.props;
    dispatch({
      type: 'devices/delChildDev',
      payload: { childDevId: id, pid: params.id },
    });
  };

  handleAdd = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'devices/addChildDevice',
      payload: {
        ...fields,
      },
      form,
      handleModalVisible,
    });
  };

  handleView = record => {
    const { isChildDetail, onChangeTab, dispatch } = this.props;
    if (isChildDetail) {
      dispatch({
        type: 'devices/fetchDetail',
        payload: record.id,
      });
      onChangeTab('1');
    } else {
      router.push({
        pathname: `/dm/devices/child/detail/${record.id}`,
        state: {
          showChildDeviceTab: record.type === 2,
          protocol: record.protocol,
          isChildDetail: true,
        },
      });
    }
  };

  render() {
    const {
      devices: { list, pagination, current, products, deviceList },
      loading,
      dispatch,
      params,
    } = this.props;

    const {
      form: { getFieldDecorator, getFieldsValue },
    } = this.props;

    const { modalVisible, selectedRowKeys } = this.state;

    const hasSelected = selectedRowKeys.length;

    const isSelected = selectedRowKeys.length === 0;

    const rowSelection = {
      selectedRowKeys,
      onChange: selectedKeys => {
        this.setState({
          selectedRowKeys: selectedKeys,
        });
      },
    };

    const clearSelect = () => {
      this.setState({
        selectedRowKeys: [],
      });
    };

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      onShowSizeChange(curr, size) {
        clearSelect();
        dispatch({
          type: 'devices/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: size } },
        });
      },
      onChange(curr) {
        clearSelect();
        dispatch({
          type: 'devices/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: pagination.currentSize } },
        });
      },
    };

    const search = value => {
      clearSelect();
      dispatch({
        type: 'devices/fetch',
        payload: { ...getFieldsValue(), ...{ name: value } },
      });
    };

    const batchEnable = () => {
      clearSelect();
      dispatch({
        type: 'devices/batch',
        payload: { type: 'enable', keys: selectedRowKeys },
      });
    };

    const batchDisable = () => {
      clearSelect();
      dispatch({
        type: 'devices/batch',
        payload: { type: 'disable', keys: selectedRowKeys },
      });
    };

    const batchDelete = () => {
      clearSelect();
      dispatch({
        type: 'devices/batch',
        payload: { type: 'delete', keys: selectedRowKeys },
      });
    };

    const parentMethods = {
      current,
      handleModalVisible: this.handleModalVisible,
      handleAdd: this.handleAdd,
      products,
      deviceList,
      dispatch,
      params,
    };

    return (
      <Fragment>
        <Form layout="inline">
          <div>
            <Row>
              <Col span={12}>
                {/* <span style={{fontSize:'16px',color:'rgba(0, 0, 0, 0.85)',fontWeight:500}}><FormattedMessage id="app.dm.devices.title" /></span> */}
                <FormItem>
                  {getFieldDecorator('name')(
                    <Search
                      className={styles.extraContentSearch}
                      placeholder={formatMessage({ id: 'app.dm.devices.search' })}
                      onSearch={search}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={12} style={{ textAlign: 'right' }}>
                {/* <FormItem>
                      <Button style={{ marginLeft: 8 }}>
                        <FormattedMessage id="app.dm.devices.add.batch" />
                      </Button>
                    </FormItem> */}
                <FormItem style={{ marginRight: 0 }}>
                  <Button
                    type="primary"
                    style={{ marginLeft: 8 }}
                    onClick={() => this.handleModalVisible(true)}
                  >
                    <FormattedMessage id="app.dm.devices.child.add" />
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </div>
          <div className={styles.tableAlert} style={{ marginTop: 15 }}>
            <Alert
              message={
                <Fragment>
                  <FormattedMessage id="app.dm.devices.table.selected" />{' '}
                  <a style={{ fontWeight: 600 }}>{hasSelected}</a>{' '}
                  <FormattedMessage id="app.dm.devices.table.selected.item" />
                  &nbsp;&nbsp;
                  <a onClick={clearSelect} style={{ marginLeft: 24 }}>
                    <FormattedMessage id="app.dm.devices.table.clear" />
                  </a>
                </Fragment>
              }
              type="info"
              showIcon
            />
          </div>
          <Table
            columns={this.columns}
            rowSelection={rowSelection}
            dataSource={list}
            pagination={false}
            loading={loading}
            rowKey="id"
          />
          <Row style={{ marginTop: 15 }}>
            <Col span={12} style={{ lineHeight: '40px', height: '40px' }}>
              <FormItem>
                <Button type="primary" disabled={isSelected} onClick={batchDelete}>
                  <FormattedMessage id="app.dm.devices.del.batch" />
                </Button>
              </FormItem>
              <FormItem>
                <Button
                  type="primary"
                  disabled={isSelected}
                  onClick={batchDisable}
                  style={{ marginLeft: 8 }}
                >
                  <FormattedMessage id="app.dm.devices.disabled.batch" />
                </Button>
              </FormItem>
              <FormItem>
                <Button
                  type="primary"
                  disabled={isSelected}
                  onClick={batchEnable}
                  style={{ marginLeft: 8 }}
                >
                  <FormattedMessage id="app.dm.devices.use.batch" />
                </Button>
              </FormItem>
            </Col>
            <Col
              span={12}
              style={{
                textAlign: 'right',
                lineHeight: '40px',
                height: '40px',
                paddingTop: '4px',
              }}
            >
              <Pagination {...paginationProps} />
            </Col>
          </Row>
        </Form>
        <ChildDeviceForm {...parentMethods} clearSelect={clearSelect} modalVisible={modalVisible} />
      </Fragment>
    );
  }
}
export default ChildDeviceManage;
